package com.xiao.springaopdemo1.annnotation;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@Aspect //将当前组件标识为切面
@Order(1)
public class loggAspectsOne {



    //公共切入点表达式
    @Pointcut("execution(* com.xiao.springaopdemo1.annnotation.CalculatorOneImpl.*(..))")
    public void Pointcut(){}



    //@Before("execution(public int com.xiao.springaopdemo1.CalculatorImpl.add(int,int))")
    //@Before("execution(* com.xiao.springaopdemo1.CalculatorImpl.*(..))")
    //前置通知
    @Before("Pointcut()")
    //切入点表达式：execution(public int com.xiao.springaopdemo1.CalculatorImpl.add(int,int))
    //execution(* com.xiao.springaopdemo1.CalculatorImpl.*(..))//这个是精确到类
    //第一个* 表示的是：任意的修饰符和返回类型
    //第的二个* 表示的是：类中任意的方法
    // (..) 表示的是：任意的参数列表
    public void method(JoinPoint joinPoint){
        //获取连接点所对应方法的签名信息
        Signature signature = joinPoint.getSignature();
        //获取连接点所对应方法的方法名
        String name = signature.getName();
        //获取连接点所对应的方法名的参数
        Object[] args = joinPoint.getArgs();
        System.out.println("hello word!"+"目标方法前");
        System.out.println("方法名："+name+",参数："+ Arrays.toString(args));
    }
    //后置通知
    @After("Pointcut()")
    public void after(){
        System.out.println("目标方法后");
    }
    //异常通知
    @AfterThrowing(value="Pointcut()",throwing="result")
    public void afterThrow(JoinPoint joinPoint,Throwable result){
        String message = result.getMessage();
        System.out.println(message.toString());
        System.out.println("异常方法");
    }
    //返回通知
    @AfterReturning("Pointcut()")
    public  void  afterReturn(){
        System.out.println("返回方法");
    }
    //环绕通知
    @Around("Pointcut()")
    public Object around(ProceedingJoinPoint joinPoint){
        Object result=null;
        try {
            System.out.println("前置通知");
            result= joinPoint.proceed();
            System.out.println("返回通知");
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }finally {
            System.out.println("后置通知");
        }
        return result ;

    }
}
